<?php
date_default_timezone_set("GMT");

//绑定 ip 到域名
// Ali::Obj()->UpdateDomainRecord();

class AliyunAPI
{
    private $accessKeyId  = "QTOlfzI9L0f4v7iR";
    private $accessSecrec = "I13fvf4xeFRoBMPCfFgoUT18oA0OJy";
    private static $obj  = null;
    public static function Obj ()
    {
        if(is_null(self::$obj))
        {
            self::$obj = new self();
        }
        return self::$obj;
    }

    public function DescribeDomainRecords($requestParams)
    {
      //   $requestParams = array(
		    // 'Action' => 'ForbidLiveStream',
		    // 'DomainName' => 'jwlive.appwuhan.com',
		    // 'AppName' => 'jw',
		    // 'StreamName' => $_GET['id'],
		    // 'LiveStreamType' => 'publisher',
      //   );
        $val =  $this->requestAli($requestParams);
        return $val;
        // $this->outPut($val);
    }


    public function mtsAliCall($requestParams)
    {
      //   $requestParams = array(
            // 'Action' => 'ForbidLiveStream',
            // 'DomainName' => 'jwlive.appwuhan.com',
            // 'AppName' => 'jw',
            // 'StreamName' => $_GET['id'],
            // 'LiveStreamType' => 'publisher',
      //   );
        $val =  $this->mtsAli($requestParams);
        return $val;
        // $this->outPut($val);
    }

    /**
     * 更新 ip
     */
    public function UpdateDomainRecord()
    {
        $ip = $this->ip();
        $requestParams = array(
            "Action"        =>  "UpdateDomainRecord",
            "RecordId"      =>  "71927383",
            "RR"            =>  "@",
            "Type"          =>  "A",
            "Value"         =>  $ip,
        );
        $val =  $this->requestAli($requestParams);
        $this->outPut($val."  ".$ip);
    }

    private function requestAli($requestParams)
    {
        $publicParams = array(
            "Format"        =>  "JSON",
            "Version"       =>  "2014-11-11",
            "AccessKeyId"   =>  $this->accessKeyId,
            "Timestamp"     =>  date(DATE_ISO8601).'Z',
            "SignatureMethod"   =>  "HMAC-SHA1",
            "SignatureVersion"  =>  "1.0",
            "SignatureNonce"    =>  substr(md5(rand(1,99999999)),rand(1,9),14),
        );

        $params = array_merge($publicParams, $requestParams);
        $params['Signature'] =  $this->sign($params, $this->accessSecrec);
        $uri = http_build_query($params);
        $url = 'https://cdn.aliyuncs.com/?'.$uri;
        return $this->curl($url);
    }


    private function mtsAli($requestParams)
    {
        $publicParams = array(
            "Format"        =>  "JSON",
            "Version"       =>  "2014-06-18",
            "AccessKeyId"   =>  $this->accessKeyId,
            "Timestamp"     =>  date("Y-m-d\TH:i:s\Z"),
            "SignatureMethod"   =>  "HMAC-SHA1",
            "SignatureVersion"  =>  "1.0",
            "SignatureNonce"    =>  substr(md5(rand(1,99999999)),rand(1,9),14),
        );

        $params = array_merge($publicParams, $requestParams);
        $params['Signature'] =  $this->sign($params, $this->accessSecrec);
        $uri = http_build_query($params);
        $url = 'https://mts.aliyuncs.com/?'.$uri;
        return $this->curl($url);
    }


    private function ip()
    {
        $ip = $this->curl("http://httpbin.org/ip");
        $ip = json_decode($ip,true);
        return $ip['origin'];
    }

    private function sign($params, $accessSecrec, $method="GET")
    {
        ksort($params);
        $stringToSign = strtoupper($method).'&'.$this->percentEncode('/').'&';

        $tmp = "";
        foreach($params as $key=>$val){
            $tmp .= '&'.$this->percentEncode($key).'='.$this->percentEncode($val);
        }
        $tmp = trim($tmp, '&');
        $stringToSign = $stringToSign.$this->percentEncode($tmp);

        $key  = $accessSecrec.'&';
        $hmac = hash_hmac("sha1", $stringToSign, $key, true);

        return base64_encode($hmac);
    }


    private function percentEncode($value=null)
    {
        $en = urlencode($value);
        $en = str_replace("+", "%20", $en);
        $en = str_replace("*", "%2A", $en);
        $en = str_replace("%7E", "~", $en);
        return $en;
    }

    private function curl($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url );
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
        $result=curl_exec ($ch);
        return $result;
    }

    private function outPut($msg)
    {
        echo date("Y-m-d H:i:s")."  ".$msg.PHP_EOL;
    }
}

// $requestParams = array(
//     'Action' => 'ForbidLiveStream',
//     'DomainName' => 'jwlive.appwuhan.com',
//     'AppName' => 'jw',
//     'StreamName' => $_GET['id'],
//     'LiveStreamType' => 'publisher',
// );


// $obj = Ali::Obj();

// echo $obj->DescribeDomainRecords($requestParams);